package com.codez.xml;

import java.io.FileOutputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.google.common.collect.Lists;

/**
 * 
 * @author 干净的代码
 * @创建时间 ： 2019-07-11
 * 
 */

public class XmlDemo2 {

	public static void main(String[] args) throws Exception {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("demos");

		List<XmlDemo> demos = Lists.newArrayList(new XmlDemo(1, "name1"),new XmlDemo(2,"name2"));
		for (XmlDemo xmlDemo : demos) {
			Element element = root.addElement("demo");
			
			element.addAttribute("a", "aa");
			element.addElement("id").setText(xmlDemo.getId().toString());
			element.addElement("name").setText(xmlDemo.getName().toString());
			element.addElement("remarks").addElement("remark").setText("123456");
		}
		
		// 设置XML文档格式
		         OutputFormat outputFormat = OutputFormat.createPrettyPrint();
		         // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1
		         outputFormat.setEncoding("UTF-8");
		         // outputFormat.setSuppressDeclaration(true); //是否生产xml头
		         outputFormat.setIndent(true); // 设置是否缩进
		         outputFormat.setIndent("    "); // 以四个空格方式实现缩进
		         outputFormat.setNewlines(true); // 设置是否换行
		         XMLWriter writer = new XMLWriter( new FileOutputStream("d:/demos.xml"),outputFormat);
		         
		         writer.write(document);
		         writer.close();
		         System.out.println("写入完毕");
		         
	}
	
}
